package com.hzh.cusviewdemo.Music;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.util.Log;

import com.blankj.utilcode.util.ObjectUtils;
import com.danikula.videocache.HttpProxyCacheServer;
import com.hzh.cusviewdemo.Activity.MusicActivity;
import com.hzh.cusviewdemo.Bean.MyMusicData;
import com.hzh.cusviewdemo.Presenter.MusicPresenter;
import com.hzh.cusviewdemo.Presenter.MusicSongData;
import com.hzh.cusviewdemo.Util.Config;
import com.hzh.cusviewdemo.Util.DialogUtils;
import com.hzh.cusviewdemo.Util.HLogUtils;
import com.hzh.cusviewdemo.Util.SugarUtils;
import com.hzh.cusviewdemo.Util.TimeUtils;

import java.util.ArrayList;
import java.util.List;

public class PlayerManagerReceiver extends BroadcastReceiver implements MusicPresenter {

    public static final String ACTION_UPDATE_UI_ADAPTER = "com.lijunyan.blackmusic.receiver.PlayerManagerReceiver:action_update_ui_broad_cast";
    private MediaPlayer mediaPlayer;
    public static int status = Constant.STATUS_STOP;  // 当前全局状态
    private int playMode; // 播放模式
    private int threadNumber;
    private Context context;
    private List<MusicSongData> songDataList = new ArrayList<>();

    public PlayerManagerReceiver() {
    }

    public PlayerManagerReceiver(Context context) {
        super();
        Log.e(Config.TAG, "PlayerManagerReceiver:构造");
        this.context = context;
        mediaPlayer = new MediaPlayer();
        initMediaPlayer();
    }

    private void initMediaPlayer() {
        NumberRandom(); // 改变线程号,使旧的播放线程停止
        String musicUrl = MyMusicUtil.getStringShared(Constant.KEY_PATH);
        int current = MyMusicUtil.getIntShared(Constant.KEY_CURRENT); // 获取现在歌曲播放进度
        if (musicUrl.equals("")) {
            return;
        }
        if (current == 0) {
            status = Constant.STATUS_STOP; // 设置播放状态为停止
        } else {
            status = Constant.STATUS_PAUSE; // 设置播放状态为暂停
        }
        MyMusicUtil.setShared(Constant.KEY_PATH, musicUrl);
        UpdateUI();
    }

    private void UpdateUI() {
        Intent musicIntent = new Intent(MusicActivity.ACTION_UPDATE_UI_MUSIC);    //接收广播为MusicUpdateMain
        musicIntent.putExtra(Constant.STATUS, status);
        context.sendBroadcast(musicIntent);

        Intent intent = new Intent(ACTION_UPDATE_UI_ADAPTER);    //接收广播为所有歌曲列表的adapter
        context.sendBroadcast(intent);
    }

    //取一个（0，100）之间的不一样的随机数
    private void NumberRandom() {
        int count;
        do {
            count = (int) (Math.random() * 100);
        } while (count == threadNumber);
        threadNumber = count;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        int cmd = intent.getIntExtra(Constant.COMMAND, Constant.COMMAND_INIT); // 默认是初始化命令
        Log.e(Config.TAG, "PMReceiver: status" + cmd);
        switch (cmd) {
            case Constant.COMMAND_INIT:    //已经在创建的时候初始化了，可以撤销了
                Log.e(Config.TAG, "COMMAND_INIT");
                break;
            case Constant.COMMAND_PLAY:
                Log.e(Config.TAG, "COMMAND_PLAY");
                status = Constant.STATUS_PLAY;
                String musicUrl = intent.getStringExtra(Constant.KEY_PATH);
                MyMusicUtil.setShared(Constant.KEY_PATH, musicUrl);
                String musicRid = intent.getStringExtra(Constant.KEY_ID);
                String musicTitle = intent.getStringExtra(Constant.KEY_TITLE);
                Log.e(Config.TAG, "PMR:URL->" + musicUrl);
                Log.e(Config.TAG, "musicRid->" + musicRid);
                if (musicUrl != null) {
                    Log.e(Config.TAG, "PMR:playMusic()");
                    // 点击
                    playMusic(musicUrl, new OnMusicPrepareOkCallBack() {
                        @Override
                        public void onPlay() {
                            MyMusicData musicDataByRid = SugarUtils.findMusicDataByRidOrSid(musicRid);
                            songDataList.clear();
                            if (musicDataByRid != null) {
                                String[] split = musicDataByRid.getLrc().split("\\^");
                                // Log.e(Config.TAG, "musicDataByLrcData: " + Arrays.toString(split));

                                // split = 许嵩 - 庐州月$00.0, 许嵩 - 庐州月$00.0, 许嵩 - 庐州月$00.0
                                for (String songLrc : split) {
                                    String[] songLrcData = songLrc.split("\\$");
                                    // 封装歌词
                                    songDataList.add(new MusicSongData(songLrcData[0], songLrcData[1]));
                                }

                                Intent updateUiIntent = new Intent(MusicActivity.ACTION_UPDATE_UI_MUSIC);
                                updateUiIntent.putExtra(Constant.STATUS, Constant.STATUS_LOAD_OK);
                                updateUiIntent.putExtra(Constant.KEY_PIC, musicDataByRid.getPic());
                                // 将歌词文件返回,String形式
                                StringBuilder lrcContent = new StringBuilder();

                                for (int i = 0; i < songDataList.size(); i++) {
                                    MusicSongData musicSongData = songDataList.get(i);
                                    if (i != songDataList.size() - 1) {
                                        lrcContent.append("[").append(formatTime(musicSongData.getTime())).append("]").append(musicSongData.getLineLyric()).append("\n");
                                    } else {
                                        lrcContent.append("[").append(formatTime(musicSongData.getTime())).append("]").append(musicSongData.getLineLyric());
                                    }
                                }
                                updateUiIntent.putExtra(Constant.KEY_LRC_LIST, lrcContent.toString());

                                // 更新本地数据的歌词
//                        MyMusicData musicDataByUrl1 = SugarUtils.findMusicDataByUrl(musicUrl);
//                        if (musicDataByUrl1 != null) {
//                            musicDataByUrl1.setLrc(lrcContent.toString());
//                            musicDataByUrl1.save();
//                        }

                                // 发送更新歌词的广播
                                context.sendBroadcast(updateUiIntent);
                            }

                            // 开启线程更新信息
                            new UpdateUIThread(PlayerManagerReceiver.this, musicTitle, songDataList, context, threadNumber).start(); // 开启一个线程通知状态到MusicActivity

                        }

                        @Override
                        public void onContinue() {
                            MyMusicData musicDataByRid = SugarUtils.findMusicDataByRidOrSid(musicRid);
                            songDataList.clear();
                            if (musicDataByRid != null) {
                                String[] split = musicDataByRid.getLrc().split("\\^");
                                // Log.e(Config.TAG, "musicDataByLrcData: " + Arrays.toString(split));
                                // split = 许嵩 - 庐州月$00.0, 许嵩 - 庐州月$00.0, 许嵩 - 庐州月$00.0
                                for (String songLrc : split) {
                                    String[] songLrcData = songLrc.split("\\$");
                                    // 封装歌词
                                    songDataList.add(new MusicSongData(songLrcData[0], songLrcData[1]));
                                }
                            }
                            // 开启线程更新信息
                            new UpdateUIThread(PlayerManagerReceiver.this, musicTitle, songDataList, context, threadNumber).start(); // 开启一个线程通知状态到MusicActivity

                        }
                    });

                } else {
                    Log.e(Config.TAG, "PMR:mediaPlayer.start()");
                    mediaPlayer.start();
                    NumberRandom();
                    if (songDataList.size() > 0) {
                        new UpdateUIThread(PlayerManagerReceiver.this, musicTitle, songDataList, context, threadNumber).start(); // 开启一个线程通知状态到MusicActivity
                    } else {
                        new UpdateUIThread(PlayerManagerReceiver.this, musicTitle, context, threadNumber).start(); // 开启一个线程通知状态到MusicActivity
                    }
                }

                break;
            case Constant.COMMAND_PAUSE:
                mediaPlayer.pause();
                Log.e(Config.TAG, "PMR：暂停音乐：" + mediaPlayer.isPlaying());
                status = Constant.STATUS_PAUSE;
                break;
            case Constant.COMMAND_STOP: //本程序停止状态都是删除当前播放音乐触发
                NumberRandom();
                status = Constant.STATUS_STOP;
                if (mediaPlayer != null) {
                    mediaPlayer.stop();
                    mediaPlayer = null;
                }
                //initStopOperate();
                break;
            case Constant.COMMAND_PROGRESS://拖动进度
                int curProgress = intent.getIntExtra(Constant.KEY_CURRENT, 0);
                Log.e(Config.TAG, "PMR收到进度：" + curProgress);
                //异步的，可以设置完成监听来获取真正定位完成的时候
                mediaPlayer.seekTo(curProgress);
                break;
            case Constant.COMMAND_RELEASE:
                NumberRandom();
                status = Constant.STATUS_STOP;
                if (mediaPlayer != null) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    mediaPlayer = null;
                }
                break;
        }
        UpdateUI();
    }

    private void initStopOperate() {
        MyMusicUtil.setShared(Constant.KEY_PATH, "https://nu01-sycdn.kuwo.cn/0e3255633b8167df14a1ca5910be6160/636c7430/resource/n2/5/93/3098436633.mp3");
    }

    public interface OnMusicPrepareOkCallBack {
        void onPlay();
        void onContinue();
    }

    /**
     * 播放歌曲
     *
     * @param musicUrl
     */
    private void playMusic(String musicUrl, OnMusicPrepareOkCallBack callBack) {
        NumberRandom();
        if (mediaPlayer != null) {
            HLogUtils.logH("playMusic 1");
            // 已在播放
            mediaPlayer.start();
            UpdateUI();
            if (callBack != null) {
                callBack.onContinue();
            }
            return;
        }
//        HLogUtils.logH("playMusic 2");
        HttpProxyCacheServer proxy = new HttpProxyCacheServer(context); // 加入音乐缓存机制
        String proxyUrl = proxy.getProxyUrl(musicUrl);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(mp -> {
            Log.e(Config.TAG, "歌曲播放完成，准备重新播放！");
            NumberRandom();                //切换线程
            MyMusicUtil.playNextMusic(context);
            UpdateUI();
        });
        if (!musicUrl.equals("")) {
            try {
                mediaPlayer.setDataSource(proxyUrl);   //设置MediaPlayer数据源
                mediaPlayer.prepareAsync();
                mediaPlayer.setOnPreparedListener(mp -> {
                    mediaPlayer.start();
                    if (callBack != null) {
                        callBack.onPlay();
                    }
                });
                mediaPlayer.setOnErrorListener((mediaPlayer, i, i1) -> {
                    // Log.e(Config.TAG, "PMR: 音乐准备出错！-----" + musicUrl);
                    return false;
                });

                // 处理外部设备控制播放命令
//                MediaSessionCompat mediaSession = new MediaSessionCompat(context, "听歌神器");
//                mediaSession.setCallback(new MediaSessionCompat.Callback() {
//                    @Override
//                    public void onPlay() {
//                        super.onPlay();
//                        Log.e(Config.TAG, "播放");
//                        Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
//                        intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
//                        intent.putExtra(Constant.KEY_TITLE, MyMusicUtil.getStringShared(Constant.KEY_TITLE));
//                        context.sendBroadcast(intent);
//                    }
//
//                    @Override
//                    public void onPause() {
//                        super.onPause();
//                        Log.e(Config.TAG, "暂停");
//                        Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
//                        intent.putExtra(Constant.COMMAND, Constant.COMMAND_PAUSE);
//                        context.sendBroadcast(intent);
//                    }
//
//                    @Override
//                    public void onSkipToNext() {
//                        super.onSkipToNext();
//                        MyMusicUtil.playNextMusic(context);
//                    }
//
//                    @Override
//                    public void onSkipToPrevious() {
//                        super.onSkipToPrevious();
//                        MyMusicUtil.playPreMusic(context);
//                    }
//                });
//                MediaSession mediaSession = new MediaSession(context, context.getPackageName());
//                mediaSession.setCallback(new MediaSession.Callback() {
//                    @Override
//                    public void onCommand(@NonNull String command, @Nullable Bundle args, @Nullable ResultReceiver cb) {
//                        super.onCommand(command, args, cb);
//                    }
//
//                    @Override
//                    public void onPlay() {
//                        super.onPlay();
//                        Log.e(Config.TAG, "MediaSession:onPlay");
//                    }
//
//                    @Override
//                    public void onPause() {
//                        super.onPause();
//                        Log.e(Config.TAG, "MediaSession:onPause");
//                    }
//                });
//
//                Intent intent = new Intent();
//                intent.setComponent(new ComponentName(context.getPackageName(), "com.hzh.cusviewdemo.Activity.MusicActivity"));
//                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.S) {
//                    mediaSession.setSessionActivity(PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE));
//                } else {
//                    mediaSession.setSessionActivity(PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
//                }
//                mediaSession.setActive(true);

//                // 设置会话为活跃状态
//                mediaSession.setActive(true);
//
//                // 设置媒体播放器为会话的播放源
//                mediaSession.setPlaybackState(new PlaybackStateCompat.Builder()
//                        .setState(PlaybackStateCompat.STATE_PLAYING, mediaPlayer.getCurrentPosition(), 1.0f)
//                        .build());
//
//
////                // 绑定到服务或活动
////                mediaSession.set(new MediaControllerCompat(context, mediaSession.getSessionToken()));
//
//                MediaMetadataCompat.Builder metadataBuilder = new MediaMetadataCompat.Builder();
//                metadataBuilder.putString(MediaMetadataCompat.METADATA_KEY_TITLE, MyMusicUtil.getStringShared(Constant.KEY_TITLE));
//                metadataBuilder.putString(MediaMetadataCompat.METADATA_KEY_ARTIST, MyMusicUtil.getStringShared(Constant.KEY_SONGER));
//                metadataBuilder.putLong(MediaMetadataCompat.METADATA_KEY_DURATION, mediaPlayer.getDuration());
//                // 设置元数据...
//                mediaSession.setMetadata(metadataBuilder.build());
            } catch (Exception e) {
                DialogUtils.showErrorToast("歌曲源文件有误，播放失败！");
                DialogUtils.showErrorToast("播放失败1！");
            }
        } else {
            DialogUtils.showErrorToast("播放失败2！");
        }


    }

    public String formatTime(String time) {
        // 时间可能为空~
        if (ObjectUtils.isEmpty(time)) {
            return "";
        }
        if (time.equals("null")) {
            return "";
        }
        return TimeUtils.stampToDateS((int) (Double.parseDouble(time) * 1000), "mm:ss.SS");
    }

    private void playNextMusic(String musicUrl, String musicRid, String musicTitle) {
        Intent intent = new Intent(MusicPlayService.PLAYER_MANAGER_ACTION);
        intent.putExtra(Constant.COMMAND, Constant.COMMAND_PLAY);
        intent.putExtra(Constant.KEY_PATH, musicUrl);
        intent.putExtra(Constant.KEY_ID, musicRid);
        intent.putExtra(Constant.KEY_TITLE, musicTitle);
        context.sendBroadcast(intent);
    }

    public MediaPlayer getMediaPlayer() {
        return mediaPlayer;
    }

    public int getThreadNumber() {
        return threadNumber;
    }

}
